import asyncio

import aiohttp

loop=asyncio.get_event_loop()

def close():
    loop.close()
    pass
taskResult =[]

# 人脸检测
async def request_run_face(file,semaphore):
    #file = "C:\\test\\docker\\ai-test\\a1.jpg"
    taskName = 'test/1'
    # 本地百度接口地址
    url = "http://127.0.0.1:8185/faceDetect?direct=true"
    # 线上百度接口地址
    #url = "http://172.17.178.7:8185/faceDetect?direct=true"
    async with semaphore:
        async with aiohttp.ClientSession()as session:
            #files = {'file': open(file, 'rb')}
            files =  open(file, 'rb')
            async with session.post(url,data=files) as resp:
                response = await resp.json()
                reqResult = {}
                reqResult["fileName"] = file
                reqResult["reqresult"] = response
                print("request_run_face response is ",response)
                taskResult.append(reqResult)
# 人脸异步协程调用
async def run_req_face(filelist):
    semaphore = asyncio.Semaphore(4)
    to_result = [request_run_face(file,semaphore) for file in filelist]
    await asyncio.wait(to_result)

# 添加百度人脸检测
def addBaiduFacetask(filesList):
    loop.run_until_complete(run_req_face(filesList))
#异步执行获取结果
async def run_req(filelist):
    semaphore = asyncio.Semaphore(4)
    to_result = [request_run(file,semaphore) for file in filelist]
    await asyncio.wait(to_result)
async def request_run(file,semaphore):
    url = "http://127.0.0.1:8185/detectHead1"
    async with semaphore:
        async with aiohttp.ClientSession()as session:
            #files = {'file': open(file, 'rb')}
            files =  open(file, 'rb')
            async with session.post(url,data=files) as resp:
                response = await resp.json()
                reqResult = {}
                reqResult["fileName"] = file
                reqResult["reqresult"] = response
                #print("response is ",response)
                taskResult.append(reqResult)
def addHeadApiTask(filelist):
    loop.run_until_complete(run_req(filelist))


